<template>
  <div id="cpsPage">
    <template v-if="!$store.state.isWatchDiypage == 0">
      <c-title :hide="false" :text="page_info.page_title"></c-title>
      <div v-if="!fullShow && showPage">
        <top_navigation v-if="top_info.group_title" :id="id" :datas="top_info" :isfollow="isfollow"></top_navigation>
        <template v-for="(item, index) in components">
          <component
            :key="index"
            :is="item.component_key"
            :isBottom="isBottom"
            :lastIndex="lastIndex"
            :btnFlag="btnFlag"
            :id="item.id"
            :page_id="page_id"
            :component_key="item.component_key"
            :datas="item.remote_data"
            :index="index"
          ></component>
        </template>
        <U_foot :id="id + '1'" v-if="(bottom_info || home_default) && $store.state.temp.item.is_decorate" :foot_type="bottom_info.foot_type" :diydatas="bottom_info"></U_foot>
      </div>

      <!--新弹窗广告和全屏广告-->
      <div class="cover">
        <div v-show="fullShow" class="fullScreen">
          <div class="full-image">
            <img :src="full_screen.image" @click="turnFullTo" />
            <span class="close"><span class="skip" @click.stop="close">跳过</span>{{ full_screen.show_time }}</span>
          </div>
        </div>
        <div class="mask" v-show="advertising.is_default === 1">
          <div
            class="modal-mask"
            v-if="advertising.datas && advertising.datas.background_over && popShow"
            :style="{ backgroundColor: `rgba(0, 0, 0, ${advertising.datas.background_over / 100})` }"
          ></div>
          <div class="mask-blank">
            <div class="pop" v-if="popShow" :class="[fun.getPhoneEnv() == 3 ? 'pcStyle' : '']">
              <div class="pop-image">
                <img :src="advertising.image" @click="turnTo2" />
                <div class="minLink" v-if="advertising.url_type == 2" @click.stop="onClickADUrl" v-html="advertising.html"></div>
                <div class="icon_close">
                  <i class="iconfont icon-close11" @click="closePop"></i>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!--新弹窗广告和全屏广告end-->
    </template>

    <!-- 没有等级浏览权限 -->
    <template v-if="$store.state.isWatchDiypage == 0">
      <div class="noPowerShow">
        <div class="warnTestBox">暂无浏览权限！</div>
      </div>
    </template>
    <!-- 没有等级浏览权限end -->
  </div>
</template>
<script>
import U_tabcontrol from "components/new_diy/tabcontrol";
window.firstAdvertisement = 1; //弹出周期设置为关闭网页(弹窗广告)
window.secondAdvertisement = 1; //弹出周期设置为关闭网页（全屏广告）
const documentElement = document.documentElement;
const body = document.body;
export default {
  data() {
    return {
      components: [],
      page_id: "",
      page_info: {},
      isBottom: false,
      btnFlag: false,

      current_page: 1,
      total_page: 0,
      isLoadMore: true,
      lastIndex: "",

      showPage: false,
      fullShow: false, //广告弹窗
      advertising: {}, //广告
      popShow: false,
      full_screen: {},
      timer: null,
      advertisement: {},

      id: "M" + new Date().getTime(), //底部导航
      bottom_info: "",
      top_info: {}, //顶部导航
      isfollow: false
    };
  },
  created() {
    this.getCPSdata();
    // mounted 肯定是第一次进来
    this.isMounted = true;
  },
  activated() {
    if (window.cps_page_id != this.fun.getKey("page_id") || window.isInHome) {
      if (!this.isMounted) {
        this.getCPSdata();
      }
    }
    this.fullShow = false;
    window.cps_page_id = this.fun.getKey("page_id");
    window.addEventListener("scroll", this.handleScroll);
    if (this.isMounted) {
      // 防止下次进入同样的页面还请求
      this.isMounted = false;
    }
  },
  deactivated() {
    window.removeEventListener("scroll", this.handleScroll);
  },
  methods: {
    // 获取装修或者是默认的数据
    getCPSdata() {
      this.showPage = false;
      $http.get("home-page.index", { page_id: this.fun.getKey("page_id") }, "加载中").then(response => {
        if (!response) return;
        if (response.result === 1) {
          this.$store.commit("setWatchDiypage", response.data.item.pageinfo.params.allowauth);
          this.showPage = true;
          //弹窗广告 --------
          if (response.data.item.page_info) {
            this.advertising = response.data.item.page_info.advertising_id || {};
            if (this.advertising.id && this.advertising.datas) {
              this.advertising.datas = JSON.parse(this.advertising.datas);
            }
            // 全屏广告
            this.full_screen = response.data.item.page_info.full_screen_id || {};
          }

          this.getParams();
          if (this.full_screen && this.full_screen.id && window.secondAdvertisement === 1 && this.full_screen.show_rule === 1) {
            window.secondAdvertisement = 0;
            this.fullShow = true;
            this.countDown(this.full_screen.show_time);
          }
          //弹窗广告 end ------
          if (response.data.item.top && response.data.item.top.id) {
            this.top_info = JSON.parse(response.data.item.top.page_info); //顶部导航数据
          }
          this.page_id = response.data.item.id;
          if (response.data.item.page) {
            this.total_page = response.data.item.page.total_page;
            this.current_page = response.data.item.page.current_page;
            this.lastIndex = response.data.item.page.count - 1;
            this.isLoadMore = true;
          }

          this.page_info = response.data.item.page_info;
          this.components = response.data.item.datas;

          let cps_foot = this.fun.isCPS() && this.fun.isCPSAPPI() && response.data.item.cps_foot_type;
          if ((cps_foot && response.data.item.cps_foot_type == -1) || response.data.item.foot_type == -1) {
            // 不显示
            this.bottom_info = "";
          } else if (response.data.item.cps_foot_type == 1 || response.data.item.foot_type == 1) {
            // 显示默认
            if (!response.data.item.foot) {
              // 显示系统默认
              this.bottom_info = {
                defaultData: true
              };
            } else {
              // 显示列表设置的默认
              if (response.data.item.foot && response.data.item.foot.page_info) {
                this.bottom_info = JSON.parse(response.data.item.foot.page_info);
              } else {
                this.bottom_info = {
                  defaultData: true
                };
              }
            }
          } else if (response.data.item.cps_foot_type == 2 || response.data.item.foot_type == 2) {
            // 显示自定义的底部导航
            if (response.data.item.foot && response.data.item.foot.id) {
              this.bottom_info = JSON.parse(response.data.item.foot.page_info);
            }
          }

          this.fun.wxShare(
            "",
            {},
            {
              title: this.page_info.page_title ? this.page_info.page_title : "",
              imgUrl: this.page_info.page_icon ? this.page_info.page_icon : "",
              description: this.page_info.page_description ? this.page_info.page_description : ""
            }
          );
          window.document.title = this.page_info.page_title;
        } else {
          this.$dialog.alert({ message: response.msg });
        }
      });
    },
    getParams() {
      let that = this;
      let _url = document.location.href;
      // 要用post  链接太长
      $http
        .post("home-page.get-params", { url: _url }, " ")
        .then(response => {
          if (response.result === 1) {
            if (window.isDecorate) {
              if (this.advertising && this.advertising.id && window.firstAdvertisement === 1 && this.advertising.show_rule === 1) {
                window.firstAdvertisement = 0;
                this.popShow = true;
                this.$nextTick(() => {
                  this.initAdvertising();
                });
              }
            } else {
              this.$route.meta.foot = false;
              this.$emit("changeFoot", this.$route.meta.foot);
            }
            if (response.data.guide) this.isfollow = true;
          } else {
            if (response.msg == "站点已关闭") {
              that.$dialog.alert({ message: response.msg });
            }
            console.log(response.msg);
          }
        })
        .catch(err => {
          console.error(err, "app");
        });
    },

    initAdvertising() {
      let that = this;
      this.getImg(this.advertising.image, function(scale) {
        // 图片加载完后获取图片高度
        let script = document.createElement("script");
        script.type = "text/wxtag-template";
        script.text = `<div style="width: ${that.clientWidth * 0.65}px;height: ${that.clientWidth * 0.65 * scale}px;"></div>`;
        that.advertising.html = `<wx-open-launch-weapp username="${that.advertising.s_id}" path="${that.advertising.s_url}">${script.outerHTML}</wx-open-launch-weapp>`;
        that.$forceUpdate();
      });
    },
    // 图片加载完回调
    getImg(url, callback) {
      let img = new Image();
      img.src = url;
      //如果图片被缓存，则直接返回缓存数据
      if (img.complete) {
        /* callback(img.width, img.height); */
        callback(Number(img.height) / Number(img.width));
      } else {
        //完全加载完毕的事件
        img.onload = function() {
          /* callback(img.width, img.height); */
          callback(Number(img.height) / Number(img.width));
        };

        img.onerror = function() {
          console.log("图片加载出错");
        };
      }
    },
    countDown(num) {
      this.full_screen.show_time = num;
      this.advertisement.time = num;
      --num;
      this.timer = setTimeout(() => {
        if (num <= 0) {
          this.fullShow = false;
          this.$route.meta.foot = false;
          this.$emit("changeFoot", this.$route.meta.foot);
        } else {
          this.countDown(num);
        }
      }, 1000);
    },
    turnFullTo() {
      if (this.full_screen.h_url) {
        if (this.full_screen.h_url !== window.location.href) {
          window.location.href = this.full_screen.h_url;
        }
      }
    },
    close() {
      this.fullShow = false;
    },
    turnTo2() {
      if (this.advertising.h_url) {
        if (this.advertising.h_url === window.location.href) {
          this.popShow = false;
        } else {
          window.location.href = this.advertising.h_url;
        }
      }
    },
    onClickADUrl() {
      if (this.fun.isCPS()) {
        // cpsApp环境下，app调用原生跳转小程序方法
        let json = {
          mini_route: this.advertising.s_url,
          mini_id: this.advertising.s_id
        };
        if (this.fun.isIosOrAndroid() === "ios") {
          miniWXIOS({ body: "miniWXIOS", json: JSON.stringify(json) });
        } else {
          miniWXAndroid(JSON.stringify(json));
        }
        return;
      }
    },
    closePop() {
      this.popShow = false;
    },
    //获取滚动条当前的位置
    getScrollTop() {
      var scrollTop = 0;
      if (documentElement && documentElement.scrollTop) {
        scrollTop = documentElement.scrollTop;
      } else if (body) {
        scrollTop = body.scrollTop;
      }
      return scrollTop;
    },
    //获取当前可视范围的高度
    getClientHeight() {
      var clientHeight = 0;
      if (body.clientHeight && documentElement.clientHeight) {
        clientHeight = Math.min(body.clientHeight, documentElement.clientHeight);
      } else {
        clientHeight = Math.max(body.clientHeight, documentElement.clientHeight);
      }
      return clientHeight;
    },
    //获取文档完整的高度
    getScrollHeight() {
      return Math.max(body.scrollHeight, documentElement.scrollHeight);
    },
    handleScroll() {
      let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      if (scrollTop > 60) {
        this.btnFlag = true;
      } else {
        this.btnFlag = false;
      }

      //滚动事件触发
      if (Number(this.getScrollTop() + this.getClientHeight() + 105) >= this.getScrollHeight()) {
        if (this.isLoadMore) {
          this.getMoreDecorate();
        }
        //此处发起请求
        this.isBottom = true;
      } else {
        this.isBottom = false;
      }
    },
    getMoreDecorate() {
      this.isLoadMore = false; // 防止多次请求分页数据
      if (this.current_page < this.total_page) {
        this.current_page = this.current_page + 1;
        $http
          .get(
            "plugin.decorate.frotend.decorate-api.get-page",
            {
              decorate_page: this.current_page,
              decorate_id: this.page_id
            },
            ".."
          )
          .then(response => {
            if (response.result == 1) {
              this.isLoadMore = true;
              this.components = this.components.concat(response.data.datas);
            } else {
              this.isLoadMore = false;
              this.current_page = this.current_page - 1;
            }
          });
      } else {
        console.log("加载完了");
      }
    }
  },
  components: {
    U_article: () => import("../../../components/new_diy/article.vue"),
    U_backup: () => import("../../../components/new_diy/backup.vue"),
    U_blank: () => import("../../../components/new_diy/blank.vue"),
    U_button: () => import("../../../components/new_diy/button.vue"),
    U_community: () => import("../../../components/new_diy/community.vue"),
    U_coupons: () => import("../../../components/new_diy/coupons.vue"),
    U_cpssearch: () => import("../../../components/new_diy/cpssearch.vue"),
    U_cube: () => import("../../../components/new_diy/cube.vue"),
    U_deposit: () => import("../../../components/new_diy/deposit.vue"),
    U_form: () => import("../../../components/new_diy/form.vue"),
    U_goods: () => import("../../../components/new_diy/goods.vue"),
    U_goodscps: () => import("../../../components/new_diy/goodscps.vue"),
    U_goodsgroup: () => import("../../../components/new_diy/goodsgroup.vue"),
    U_ywmgroup: () => import("../../../components/new_diy/ywmgroup.vue"),
    U_goodsnearby: () => import("../../../components/new_diy/goodsnearby.vue"),
    U_goodsrush: () => import("../../../components/new_diy/goodsrush.vue"),
    U_headline: () => import("../../../components/new_diy/headline.vue"),
    U_homedata: () => import("../../../components/new_diy/homedata.vue"),
    U_line: () => import("../../../components/new_diy/line.vue"),
    U_livestreaming: () => import("../../../components/new_diy/livestreaming.vue"),
    U_location: () => import("../../../components/new_diy/location.vue"),
    U_lottery: () => import("../../../components/new_diy/lottery.vue"),
    U_maps: () => import("../../../components/new_diy/maps.vue"),
    U_notice: () => import("../../../components/new_diy/notice.vue"),
    U_richtext: () => import("../../../components/new_diy/richtext.vue"),
    U_search: () => import("../../../components/new_diy/search.vue"),
    U_staff: () => import("../../../components/new_diy/staff.vue"),
    U_shopfor: () => import("../../../components/new_diy/shopfor.vue"),
    U_shortvideo: () => import("../../../components/new_diy/shortvideo.vue"),
    U_signin: () => import("../../../components/new_diy/signin.vue"),
    U_simplegraph: () => import("../../../components/new_diy/simplegraph.vue"),
    U_slideshow: () => import("../../../components/new_diy/slideshow.vue"),
    U_stores: () => import("../../../components/new_diy/stores.vue"),
    U_storesranking: () => import("../../../components/new_diy/storesranking.vue"),
    U_suspendbutton: () => import("../../../components/new_diy/suspendbutton.vue"),
    U_tabcontrol,
    U_title: () => import("../../../components/new_diy/title.vue"),
    U_video: () => import("../../../components/new_diy/video.vue"),
    top_navigation: () => import("../../../components/new_diy/top_navigation.vue"),
    U_foot: () => import("../../../components/new_diy/foot.vue")
  }
};
</script>
<style lang="scss" rel="stylesheet/scss" scoped>
/* #cpsPage {} */
.cover .fullScreen {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 9999;
}

.cover .fullScreen .full-image {
  position: relative;
  width: 100%;
  height: 100%;
}

.cover .fullScreen .full-image img {
  width: 100%;
  height: 100%;
}

.cover .fullScreen .full-image .close {
  position: absolute;
  right: 1rem;
  top: 1rem;
  color: #fff;
  font-size: 16px;
}

.cover .fullScreen .full-image .close .skip {
  margin-right: 0.5rem;
}

.cover .mask-blank .pop {
  width: 65%;
  position: fixed;
  z-index: 8888;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

.cover .mask-blank .pop.pcStyle {
  width: 270px;
}

.cover .mask-blank .pop .pop-image {
  position: relative;
}

.cover .mask-blank .pop .pop-image img {
  width: 100%;
  height: 100%;
}

.cover .mask-blank .pop .pop-image .icon_close {
  top: 0;
  right: 0;
  position: absolute;
  background-color: #333;
  width: 1.5rem;
  height: 1.5rem;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: -0.75rem;
  margin-right: -0.75rem;
  border-radius: 50%;
}

.cover .mask-blank .pop .pop-image .icon_close {
  color: #fff;
}

.noPowerShow {
  width: 100%;
  height: 100vh;
  overflow: hidden;
  background: #999;
  position: relative;

  .warnTestBox {
    position: absolute;
    display: inline-block;
    top: 50%;
    left: 50%;
    margin-top: -1.5rem;
    margin-left: -5rem;
    color: #fff;
    width: 10rem;
    height: 3rem;
    line-height: 3rem;
    border-radius: 0.5rem;
    background: #333;
  }
}
</style>
